<?php
abstract class Nextapp_Options
{
	const ELEMENT_TEXT = 'text';
	const ELEMENT_SELECT = 'select';
	const ELEMENT_RADIO = 'radio';
	const ELEMENT_CHECKBOX = 'checkbox';
	
	abstract function getType();
	
	abstract function getName();
	
	abstract function getDefault();
	
	public function getId()
	{
		return $this->getName();
	}
	
	public function getTitle()
	{
		$this->getName();
	}
	
	public function getValue()
	{
		$value = get_option($this->getName(), null);
		return is_null($value) ? $this->getDefault() : $value;
	}
	
	protected function before()
	{
		return '';
	}
	
	protected function after()
	{
		return '';
	}
	
	public function render($value = null)
	{
		if (is_null($value)) {
			$value = $this->getValue();
		}
		
		$html = '';
		switch ($this->getType()) {
			case self::ELEMENT_CHECKBOX:
				$html .= '<input type="checkbox" name="' . $this->getName() . '" id="' . $this->getId() . '" value="' . $value . '"/>';
				break;
			case self::ELEMENT_TEXT:
				$html .= '<input type="text" name="' . $this->getName() . '" id="' . $this->getId() . '" value="' . $value . '"/>';
				break;
			case self::ELEMENT_RADIO:
				$html .= '<input type="radio" name="' . $this->getName() . '" id="' . $this->getId() . '" value="' . $value . '"/>';
				break;
			case self::ELEMENT_SELECT:
				$html .= '<select name="' . $this->getName() . '" id="' . $this->getId() . '">';
				if (method_exists($this, 'getOptions')) {
					foreach ($this->getOptions() as $key => $label) {
						$selected = $value == $key ? ' selected="selected"' : '';
						$html .= '<option value="' . $key . '"' . $selected . '>' . $label . '</option>';
					}
				}
				$html .= '</select>';
			default:
				break;
		}
		return $this->before() . $html . $this->after();
	}
}